var mgeOrg = {
    tableid: "table1",
    treetable: null,
    iconlay: null,
    layerindex: null,
    expand: false
};
/**
 * 初始化表格的列
 */
mgeOrg.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '机构ID', field: 'id', visible: false, align: 'center', valign: 'middle', width: '180px'},
        {title: '机构名称', field: 'orgName', align: 'center', valign: 'middle', sortable: true, width: '280px'},
        {
            title: '机构编码', field: 'orgCode', align: 'center', valign: 'middle', sortable: true, width: '100px'
        },
        {
            title: '创建时间', field: 'createTime', align: 'center', valign: 'middle', sortable: true, width: '100px'
        },
        {
            title: '排序号', field: 'orgSort', align: 'center', valign: 'middle', sortable: true, width: '100px'
        },
        {
            title: '操作', align: 'center', valign: 'middle', sortable: true, width: '150px',
            formatter: function (value, row, index) {
                var actions = [];
                actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="mgeOrg.updateShow(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                actions.push('<a class="btn btn-info btn-xs " href="javascript:void(0)" onclick="mgeOrg.addNode(\'' + row.id + '\')"><i class="fa fa-plus"></i>新增</a> ');
                actions.push('<a class="btn btn-danger btn-xs " href="javascript:void(0)" onclick=" mgeOrg.ajaxDelete(\'' + row.id + '\');"><i class="fa fa-trash"></i>删除</a>');
                return actions.join('');
            }
        }
    ]
    return columns;
};
mgeOrg.getTree = function () {
    var ajaDataFilter = function (treeid, parentNode, respsnseData) {
        if (respsnseData != null && respsnseData.code == "200") {
            if (parentNode == null) {
                var data = [
                    {
                        id: 0, name: "功能目录", children: respsnseData.data
                    }
                ];
                return data;
            } else {
                return respsnseData.data;
            }
        }
        return [
            {}
        ];
    }
    $.fn.zTree.init($("#funtree1"), {
        view: {
            dblClickExpand: false
        }, async: {
            enable: true, url: ctx + "/mge/adx/org/getOrgTree", dataFilter: ajaDataFilter, autoParam: ["id"]
        }, data: {}, callback: {
            beforeClick: function () {
                return true;
            }, onClick: function (e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("funtree1"), nodes = zTree
                    .getSelectedNodes();
                if (nodes.length > 0) {
                    var cityObj = $("#parentId_chosen").find("span");
                    $(cityObj).html(nodes[0].name);
                    $("#pid").val(nodes[0].id);
                    $("#pid").parent().parent().addClass("has-success").removeClass("has-error");
                    $("#pid").next().html("");
                }

            }
        }
    });
}

mgeOrg.comboxTree = function () {

    var hideMenu = function () {
        $("#treeContent").fadeOut("fast");
        $("body").unbind("mousedown", onBodyDown);
    }

    var onBodyDown = function (event) {
        if (!(event.target.id == "menuBtn" || event.target.id == "treeContent" || $(event.target)
            .parents("#treeContent").length > 0)) {
            hideMenu();
        }
    }
    $("#parentId_chosen").on('click', function () {
        var cityObj = $(this);
        var cityOffset = $(this).offset();
        $("#treeContent").css({
            left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px"
        }).slideDown("fast");
        $("#treeContent").width($(this).width());
        $("body").bind("mousedown", onBodyDown);
    });
}
mgeOrg.openDlg = function (title) {
    var hei = $(window).height() - 20;
    var wi = $(window).width() - 20;
    mgeOrg.clearInputs();
    mgeOrg.layerindex = layer.open({
        type: "1",
        title: title ? title : "添加",
        area: [(wi > 650 ? 650 : wi) + 'px', (hei > 500 ? 500 : hei) + 'px'],
        shade: 0.4,
        maxmin: true,
        btn: ["确定", "取消"],
        content: $("#orgopt"),
        scrollbar: false,
        success: function (layero, index) {
        },
        yes: function (index) {
            //mgeRole.postAjaxFrom();
            $("#form_opt").submit();
            mgeOrg.layerindex = index;
        }, btn2: function (index) {
            // mgeOrg.clearInputs();
        }, cancel: function () {
            //mgeOrg.clearInputs();
        }
    });
};
/**
 * 检查是否选中
 */
mgeOrg.check = function () {
    var selected = $('#' + this.tableid).bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        //Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        // Menu.seItem = selected[0];
        return true;
    }
};
mgeOrg.addOnClick = function () {
    $("#add").on("click", function (e) {
        e.preventDefault();
        mgeOrg.openDlg();

    });
}
mgeOrg.addNode = function (id) {
    mgeOrg.openDlg();

    debugger
    var sapn = $("#parentId_chosen").find("span");
    var str = "";
    $("#pid").val(id);
    if (id == "0") {
        str = "功能目录";
    } else {
        var ztree = $.fn.zTree.getZTreeObj("funtree1");
        var nodes = ztree.getNodes();
        if (nodes.length > 0) {
            str = mgeOrg.getNodesName(nodes[0], id);
        }
        var f = ztree.getNodeByParam("id", id, null);
        ztree.selectNode(f);
    }
    sapn.html(str);
}
mgeOrg.expOnClick = function () {
    $("#exp").on('click', function () {
        debugger
        if (!mgeOrg.expand) {
            mgeOrg.treetable.onExpandAll();

        } else {
            mgeOrg.treetable.onCollapseAll();
        }
        mgeOrg.expand = !mgeOrg.expand;
    })
}

mgeOrg.updateOnClick = function () {
    $("#update").on('click', function (e) {
        e.preventDefault();
        var row = mgeOrg.treetable.getSelections();
        if (row == null) {
            layer.alert("请选中您要修改数据！");
            return false;
        }
        mgeOrg.updateShow(row.id);
    });
}
mgeOrg.updateShow = function (id) {
    mgeOrg.openDlg("修改");
    mgeOrg.getByOrgid(id);
}

mgeOrg.delOnClick = function () {
    $("#del").on('click', function (e) {
        e.preventDefault();
        var row = mgeOrg.treetable.getSelections();
        if (row == null) {
            layer.alert("请选中您要修改数据！");
            return false;
        }
        mgeOrg.ajaxDelete(row.id);
    });
}
mgeOrg.ajaxDelete = function (id, row) {
    var cof = layer.confirm("您确定要删除数据吗？", {title: ["确认", "font-size:14px;font-weight:bold;"]}, function () {
        layer.close(cof)
        var lay = layer.load({shade: [0.1]});
        $.ajax({
            url: ctx + "/mge/adx/org/delOrg",
            data: {id: id},
            type: "post",
            dataType: "json",
            success: function (data, sta) {
                layer.close(lay);
                if (data != null && data.code == '200') {
                    cmm.layerMessge("删除成功");
                    if (!row) {
                        row = mgeOrg.treetable.getSelections();
                        if (row != null) {
                            if (row && row.tr) {
                                row.tr.remove();
                            }
                        }
                    }
                }
            },
            error: function (sta) {
                layer.close(lay);
                layer.alert("请求失败，请重试或检查网络！");
            }
        });

    }, function () {

    })
}
mgeOrg.search = function () {
    mgeOrg.treetable.refresh({query: cmm.serializeObject($("#form_search"))});
}
mgeOrg.resHeigth = function () {
    var he = $(window).height() - 10;
    return he;
}
mgeOrg.postAjaxFrom = function () {
    $("#form_opt").validate({
        rules: {
            orgName: {
                "required": true, maxlength: 50, textChvail: true
            },
            orgCode: {"required": true, maxlength: 100, textEnvail: true},
            pid: {"required": true},
            orgSort: {"required": false, maxlength: 10, textEnvail: true}
        }, messages: {
            orgName: {"required": "请输入部门名称", maxlength: "最大50字符"},
            orgCode: {"required": "部门编码", maxlength: "最大100字符"},
            pid: {"required": "请选择上级模块"},
            orgSort: {maxlength: "最大10字符"}
        }, success: function (label) {

        }, onkeyup: function (element) {
            $(element).valid();
        }, onfocusout: false, errorElement: "em", errorPlacement: function (error, element) {
            $(error).css({"color": "red", "font-size": "15px"});
            $(element).parent().append(error);
        }, highlight: function (element, errorClass, validClass) {
            var md = $(element).parent().parent().addClass("has-error").removeClass("has-success");
        }, unhighlight: function (element, errorClass, validClass) {
            $(element).parent().parent().addClass("has-success").removeClass("has-error");
        }, submitHandler: function () {
            if (!$("#form_opt").valid()) {
                return false;
            }
            if ($("#pid").val() == "") {
                $("#pid").parent().append($("<em>请选择上级模块</em>").css({"color": "red", "font-size": "15px"}));
                $("#pid").parent().parent().addClass("has-error").removeClass("has-success");
                return false;
            }
            mgeOrg.ajax();
            return false;
        }
    });
}
mgeOrg.getByOrgid = function (id) {
    var lay = layer.load({shade: [0.1]});
    $.ajax({
        url: ctx + "/mge/adx/org/getOrgByid",
        data: {id: id},
        dataType: "json",
        type: 'post',
        success: function (d, s) {
            layer.close(lay);
            if (d.code == '200') {
                debugger
                cmm.fromData(d.data);
                var sapn = $("#parentId_chosen").find("span");
                var str = "";
                if (d.data.pid == "0") {
                    str = "功能目录";
                } else {
                    var ztree = $.fn.zTree.getZTreeObj("funtree1");
                    var nodes = ztree.getNodes();
                    if (nodes.length > 0) {
                        str = mgeOrg.getNodesName(nodes[0], d.data.pid);
                    }
                }
                sapn.html(str);
                $("#form_opt").valid();
            } else {
                layer.alert(d.message);
            }
        }, error: function (sta) {
            layer.close(lay);
            layer.alert("请求失败，请重试或检查网络！");
        }
    });
}
mgeOrg.treeRefresh = function (v) {
    var ztree = $.fn.zTree.getZTreeObj(v);
    ztree.reAsyncChildNodes(ztree.getNodeByParam('id', $("#pid").val(), null), "refresh", true);
}
mgeOrg.ajax = function () {
    var lay = layer.load(0, {shade: [0.1]});
    debugger
    if ($("#id").val() == "") {
        $.ajax({
            url: ctx + "/mge/adx/org/addOrUpageOrg",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeOrg.layerindex);
                if (data.code == '200') {
                    mgeOrg.treetable.refresh();
                    mgeOrg.treeRefresh("funtree1");
                    mgeOrg.clearInputs();
                    cmm.layerMessge("添加成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    } else {
        $.ajax({
            url: ctx + "/mge/adx/org/addOrUpageOrg",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeOrg.layerindex);
                if (data.code == '200') {
                    mgeOrg.treeRefresh("funtree1");
                    mgeOrg.treetable.refresh();
                    mgeOrg.clearInputs();
                    cmm.layerMessge("修改成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    }
}
mgeOrg.clearInputs = function () {
    var ipts = $("#form_opt").find("[data-type='rep']");
    if (ipts.length > 0) {
        ipts.each(function (i, v) {
            $(v).val("");
            var er = $(v).next();
            if (er.length > 0 && $(er).prop("nodeName").toLowerCase() == "em") {
                er.remove();
                var hs = $(v).parent().parent();
                hs.removeClass("has-success");
                hs.removeClass("has-error");
            }
        });
    }
    var treeObj = $.fn.zTree.getZTreeObj("funtree1");
    var nodes = treeObj.getSelectedNodes();
    if (nodes.length > 0) {
        treeObj.cancelSelectedNode(nodes[0]);
    }
    $("#orgSort").val("10");
    $("#id").val("");
    $("#parentId_chosen").find("span").html("");
}
mgeOrg.getNodesName = function (nodes, id) {
    if (nodes && nodes.children && nodes.children.length > 0) {
        for (var i = 0; i < nodes.children.length; i++) {
            if (nodes.children[i].id == id) {
                return nodes.children[i].name;
            } else {
                var ss = mgeOrg.getNodesName(nodes.children[i], id);
                if (ss != "") {
                    return ss;
                }
            }
        }
        return "";
    } else {
        return "";
    }
}

$(function () {
    var defaultColunms = mgeOrg.initColumn();
    var table = new BSTreeTable(mgeOrg.tableid, ctx + "/mge/adx/org/listOrg?rad=" + new Date().getTime(), defaultColunms);
    table.setExpandColumn(2);
    table.setIdField("id");
    table.setCodeField("id");
    table.setParentCodeField("pid");
    table.setExpandAll(mgeOrg.expand);
    table.setOnLoadSuccess(function (data) {
        if (data.code == '200') {
            return data.rows;
        }
        return [];
    });
    table.init();
    mgeOrg.addOnClick();
    mgeOrg.updateOnClick();
    mgeOrg.delOnClick();
    mgeOrg.expOnClick();
    mgeOrg.postAjaxFrom();
    mgeOrg.getTree();
    mgeOrg.comboxTree();
    mgeOrg.treetable = table;

});
